/*
* Copyright 2010 Dovado FZ-LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*       http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/


#import "RouterViewController.h"
#import "DovadoAppDelegate.h"
#import "DialogUtils.h"
#import "Info.h"
#import "DovadoEnableAPI.h"
#import "DovadoEnableAPIListener.h"

@implementation RouterViewController
@synthesize mNetworkRequest;
@synthesize mRouterText;
@synthesize mRouterText4GR;
@synthesize mRouterText3GN;
@synthesize mRouterTextUMR;
@synthesize enableAPI;


- (void) alertView:(UIAlertView *)alertEnableAPIConfirm clickedButtonAtIndex:(NSInteger)buttonIndex {
	NSLog(@"ClickButtonAtIndex");
	if(buttonIndex == 1) {
		NSLog(@"Do it!!");
		mProgressAlert = [DialogUtils createProgressionAlertWithTitle:NSLocalizedString(@"about_text_router_alert_wait_title", @"Please wait") 
														   andMessage:NSLocalizedString(@"about_text_router_alert_wait_message", @"Trying to communicate with router")];
		[enableAPI enableAPI];
	}
}

/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
 if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
 // Custom initialization
 }
 return self;
 }
 */

/*
 * Starts the download of available information from the router.
 */
- (void) syncAllData {	
	request_error_codes_t errorCode = [mNetworkRequest requestSyncAll];
	if (errorCode == REQUEST_OK) {
		mProgressAlert = [DialogUtils createProgressionAlertWithTitle:NSLocalizedString(@"synching_aliases_alert_title", @"Please wait") 
														   andMessage: NSLocalizedString(@"synching_aliases_alert_message", @"Downloading available aliases")];
	} else {
		[DialogUtils showConnectionFailedDialog:errorCode];
	}
}

- (void)viewDidLoad {
	[super viewDidLoad];
	mRouterText.font= [UIFont systemFontOfSize:10];
	mRouterText4GR.font= [UIFont systemFontOfSize:10];
	mRouterText3GN.font= [UIFont systemFontOfSize:10];
	mRouterTextUMR.font= [UIFont systemFontOfSize:10];
	mRouterText.text = NSLocalizedString(@"router_text", @"This is an application used for controlling a remote powerswitch connected to your Dovado-router");
	mRouterText4GR.text = NSLocalizedString(@"router_text4GR", @"This is an application used for controlling a remote powerswitch connected to your Dovado-router");
	mRouterText3GN.text = NSLocalizedString(@"router_text3GN", @"This is an application used for controlling a remote powerswitch connected to your Dovado-router");
	mRouterTextUMR.text = NSLocalizedString(@"router_textUMR", @"This is an application used for controlling a remote powerswitch connected to your Dovado-router");
	mNetworkRequest = NULL;
	enableAPI = [[DovadoEnableAPI alloc] initWithListener:self];
}

- (void) postLogin {
	DovadoAppDelegate *appDelegate = (DovadoAppDelegate*)[[UIApplication sharedApplication] delegate];	
	if (mNetworkRequest == NULL) {
		mNetworkRequest = [[DovadosNetworkRequest alloc] initWithHost: appDelegate.mHostAddress :6435];
	} else {
		[mNetworkRequest setMHost:appDelegate.mHostAddress];
	}
	[mNetworkRequest setUserInformation:appDelegate.mUser :appDelegate.mPassword: self];
	[self syncAllData]; //response will be given.
}

- (void)connectionTimeOut:(NSTimer*)timer {
	UIProgressView *progress = [timer userInfo];
	if(progress.progress < 1.0f){
		progress.progress += 1.0/80;
	} else {
		[progress release]; 
		[timer invalidate];
		[mProgressAlert dismissWithClickedButtonIndex:0 animated:TRUE];
		[mProgressAlert release];
		
		/* TODO: Maybe login afterwards ?? */
		[self postLogin];
	}
}

- (void) viewDidAppear:(BOOL)animated {
	NSLog(@"RouterViewController: viewDidAppear");
	[super viewDidAppear:(BOOL)animated];
	DovadoAppDelegate *appDelegate = (DovadoAppDelegate*)[[UIApplication sharedApplication] delegate];
	if(appDelegate.justLoggedIn == TRUE) {
		[appDelegate setJustLoggedIn:FALSE];
		[self postLogin];
	}
}

/*
 // Override to allow orientations other than the default portrait orientation.
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 // Return YES for supported orientations
 return (interfaceOrientation == UIInterfaceOrientationPortrait);
 }
 */

-(IBAction) onURLLabelClicked {
	NSURL *url = [NSURL URLWithString:@"http://www.dovado.com"];
	[[UIApplication sharedApplication] openURL:url];
}
-(IBAction) onURL4GRClicked {
	NSURL *url = [NSURL URLWithString:@"http://www.dovado.com/4gr"];
	[[UIApplication sharedApplication] openURL:url];
}
-(IBAction) onURL3GNClicked {
	NSURL *url = [NSURL URLWithString:@"http://www.dovado.com/3gn"];
	[[UIApplication sharedApplication] openURL:url];
}


- (void) syncAllRequestDone: (NSMutableArray*) groupsArray: (NSMutableArray*) aliasArray: (NSMutableArray*) infoArray {
	DovadoAppDelegate *appDelegate = (DovadoAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	if (groupsArray != NULL) {
		NSMutableArray *tmpGroupsArray = [[NSMutableArray alloc] init];
		for(Info *group in groupsArray) {
			[tmpGroupsArray addObject:group];
		}
		if (appDelegate.mGroupsArray != NULL) {
			[appDelegate.mGroupsArray release];
		}
		appDelegate.mGroupsArray = tmpGroupsArray;
	}
	
	if (aliasArray != NULL) {
		NSMutableArray *tmpAliasArray = [[NSMutableArray alloc] init];
		for(Info *alias in aliasArray) {
			[tmpAliasArray addObject:alias];
		}
		if (appDelegate.mAliasArray != NULL) {
			[appDelegate.mAliasArray release];
		}
		appDelegate.mAliasArray = tmpAliasArray;
	}
	
	if (infoArray != NULL) {
		CLLocationCoordinate2D coords;
		coords.latitude = appDelegate.mRouterLocation.latitude;
		coords.longitude = appDelegate.mRouterLocation.longitude;
		NSMutableArray *tmpInfoArray = [[NSMutableArray alloc] init];
		for(Info *info in infoArray) {
			[tmpInfoArray addObject:info];
			
			if([info.mName isEqualToString:@"GPS_LAT"]) {
				coords.latitude = [info.mValue floatValue];
			} else if([info.mName isEqualToString:@"GPS_LONG"]) {
				coords.longitude = [info.mValue floatValue];
			}			
		}
		appDelegate.mRouterLocation = coords;
		if (appDelegate.mInfoArray != NULL) {
			[appDelegate.mInfoArray release];
		}
		appDelegate.mInfoArray = tmpInfoArray;
	}
	
	
	/* Login was correct, now store the username, password and hostname */
	[appDelegate storeSharedPrefs];
	
	[DialogUtils dismissAlert:mProgressAlert];
	mProgressAlert = NULL;
}

- (void) dovadoRequestFailed: (request_listener_error_t) error_code: (NSString*) message {
	NSLog(@"dovadoRequestFailed error_code: %i message: %@", error_code, message);
	[DialogUtils dismissAlert:mProgressAlert];
	mProgressAlert = NULL;
	if(error_code == ERROR_UNKNOWN_ERROR) {
		UIAlertView *errorAlert = [[UIAlertView alloc]
								   initWithTitle: NSLocalizedString(@"on_result_exception_dialog_title", @"Network Error")
								   message: NSLocalizedString(@"error_unknown_error", @"Unknown error")
								   delegate:self
								   cancelButtonTitle:NSLocalizedString(@"no_button_text", @"No")
								   otherButtonTitles:NSLocalizedString(@"yes_button_text", @"Yes"), nil];
		((UILabel*)[[errorAlert subviews] objectAtIndex:1]).textAlignment = UITextAlignmentLeft;
		[errorAlert show];
		[errorAlert release];
	} else {
		[DialogUtils showOnConnectionResultErrorDialog:error_code];
	}
}

- (void) dovadoEnableAPICallback: (enable_api_listener_status_t) status_code {
	NSLog(@"mProgressAlert %@", mProgressAlert);
	[DialogUtils dismissAlert:mProgressAlert];
	mProgressAlert = NULL;
	switch (status_code) {
		case STATUS_FAILED:
			NSLog(@"status_failed");
			[DialogUtils showDialog:NSLocalizedString(@"about_text_router_alert_error_alert_title", @"Connection failed") 
						 andMessage:NSLocalizedString(@"about_text_router_alert_error_alert_message", @"Could not establish a connection to your router.")];
			break;
		case STATUS_OLD_FIRMWARE:
			NSLog(@"status_old_firmware");
			[DialogUtils showDialog:NSLocalizedString(@"about_text_router_alert_error_alert_title", @"Connection failed") 
						 andMessage:NSLocalizedString(@"about_text_router_alert_error_alert_message", @"Could not establish a connection to your router.")];
			break;
		case STATUS_TIMEOUT:
			NSLog(@"status_timeout");
			[DialogUtils showDialog:NSLocalizedString(@"about_text_router_alert_error_alert_title", @"Connection failed") 
						 andMessage:NSLocalizedString(@"about_text_router_alert_error_alert_message", @"Could not establish a connection to your router.")];
			break;
		case STATUS_OK:
			NSLog(@"status_ok");
			//[DialogUtils showDialog:NSLocalizedString(@"about_text_router_alert_sucessful_title", @"Sucessful") 
			//			 andMessage:NSLocalizedString(@"about_text_router_alert_sucessful_message", @"Sucessful")];
			/* Show progress bar */
			mProgressAlert = [[UIAlertView alloc] initWithTitle: NSLocalizedString(@"about_text_router_alert_sucessful_title", @"Sucessful")
														message: NSLocalizedString(@"about_text_router_alert_sucessful_message", @"Sucessful")
													   delegate: self
											  cancelButtonTitle: nil
											  otherButtonTitles: nil];

			// Create the progress bar and add it to the alert
			UIProgressView *progress = [[UIProgressView alloc] initWithFrame:CGRectMake(30.0f, 145.0f, 225.0f, 90.0f)];
			[mProgressAlert addSubview:progress];
			[progress setProgressViewStyle: UIProgressViewStyleBar];
			progress.progress = 0;
			
			NSTimer *timer = [NSTimer timerWithTimeInterval:1.0f target:self selector:@selector(connectionTimeOut:) userInfo:progress repeats:YES];
			[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
			[mProgressAlert show];
			break;
	}
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
	[mRouterText release];
	[mRouterText4GR release];
	[mRouterText3GN release];
	[mRouterTextUMR release];
	[enableAPI release];
	[super dealloc];
}


@end
